<?php
if (!isset($_SESSION)) session_start();
 (!isset($_SESSION["email"])) header("location:dangnhap.php");

if (!isset($_SESSION["giohang"]))
	{
		echo "KHang can chon SP de mua hang. "; echo "&nbsp; <a href=sanpham.php>Xem hang</a>"; exit;
	}


include "connect.php";

function getMaxDonHang()
{
	$sql ="select mahd from hoadon order by mahd desc limit 0, 1 ";
	$kq = mysql_query($sql);
	$r =mysql_fetch_array($kq);
	return $r[0];
}

function insertChiTietHoaDon($mahd, $gh)
{

	foreach($gh as $m =>$sl)
		{	
			$sql ="select * from dongho where madh='$m' ";
			$kq = mysql_query($sql);
			if (mysql_num_rows($kq)>0)
			{
				$r =mysql_fetch_array($kq);
				$gia = $r['gia'];
				$sql = "insert into chitiethd(mahd, madh, soluong, gia )";
				$sql .=" values('$mahd', '$m', '$sl', '$gia') ";
				//echo "<br> $sql ";
				mysql_query($sql);
			}
		}
}

function insertHoaDon()
{
	$email = $_SESSION['email'];
	$mahd = $email ."_".time();
	$giohang = $_SESSION['giohang'];
	$tennguoinhan = $_POST['tennguoinhan'];
	$diachinguoinhan = $_POST['diachinguoinhan'];
	$dienthoainguoinhan = $_POST["dienthoainguoinhan"];
	$ngaynhan = $_POST["ngaynhan"];
	$sql ="Insert into hoadon(mahd, email, ngayhd, tennguoinhan, diachinguoinhan, ngaynhan, dienthoainguoinhan )";
	$sql .=" values('$mahd', '$email', NOW(), '$tennguoinhan', '$diachinguoinhan', '$ngaynhan', '$dienthoainguoinhan')";
	mysql_query($sql);
	echo "<br> --- $sql ";
	
	//$mahd = getMaxDonHang();
	insertChiTietHoaDon($mahd, $giohang);
	unset($_SESSION["giohang"]);
}
//Gui email toi khach hang tai day...
insertHoaDon();
//su dung ham mail() de gui noi dung gio hang toi email KH

?>
<style>
div {-moz-border-radius: 5px; -webkit-border-radius: 5px; border: 1px solid #CCCCCC; 
padding: 10px; background:#af012; width:700px; left:191px; background-color:#CFC; margin:20px}
</style>
<div>
Cam On Qui Khach da mua hang<br>
Thong tin mua hang da gui toi email :<?php echo $_SESSION["email"];?><br>

Bam vao <a href ="sanpham.php"> Day </a> De tiep tuc mua hang.
</div>